/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.demo.actions;

import opiam.admin.applis.demo.beans.Person;
import opiam.admin.applis.demo.utils.GenerateTree;

import opiam.admin.faare.config.javabeans.JBProfile;
import opiam.admin.faare.service.UserContext;
import opiam.admin.faare.service.services.views.TreeNode;
import opiam.admin.faare.service.services.views.ViewGenerator;
import opiam.admin.faare.struts.actions.SecureAction;
import opiam.admin.faare.struts.taglib.MenuDefineTag;
import opiam.admin.faare.struts.utils.SessionContext;

import org.apache.log4j.Logger;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;


/**
 * This class allows to choose a profile and to define the treeView.
 */
public class ProfileAction extends SecureAction
{
    /** Instance of the log4j logger.
     * Used to generate the execution traces. */
    private static Logger _logger =
        Logger.getLogger(ProfileAction.class.getName());

    /**
     * This method is called to execute the action.
     *
     * @param mapping              Struts mapping data.
     * @param actionForm           FormBean associated with the action.
     * @param request              HTTP request.
     * @param httpServletResponse  HTTP response.
     *
     * @return An ActionForward.
     *
     * @throws IOException  An I/O exception if failed or interrupted I/O operations occurs.
     * @throws ServletException  A ServletException if the servlet has a problem.
     */
    @Override
	public ActionForward secureExecute(ActionMapping mapping,
                                       ActionForm actionForm,
                                       HttpServletRequest request,
                                       HttpServletResponse httpServletResponse
                                      ) throws IOException, ServletException
    {
        SessionContext sessionContext = null;
        UserContext userContext = null;
        ActionMessages msgErrors = new ActionMessages();

        try
        {
            // Gets the session.
            HttpSession session = request.getSession();

            // Gets the session context.
            sessionContext = SessionContext.getInstance(session);

            // Gets the user context.
            userContext = sessionContext.getUserContext();

            String profileIdxStr =
                (String) ((DynaActionForm) actionForm).get("profileIdx");

            _logger.debug("profileIdxStr = " + profileIdxStr);
            _logger.debug("profile= " + userContext.getJbProfile().getName());

            int profileIdx = Integer.parseInt(profileIdxStr);

            // Removes the menus.
            session.removeAttribute(MenuDefineTag.USER_MENUS_SESSION_ATTR);

            // Puts the selected profile in the userContext
            userContext.chooseProfile(profileIdx);

            _logger.debug("selected profile= " +
                          userContext.getJbProfile().getName()
                         );

            // Modifies the profile of the user.
            JBProfile profile = userContext.getJbProfile();
            Person user = (Person) userContext.getJbUser();
            user.setProfile(profile.getName());

            // Initializes the navigation
            TreeNode treeNode =
                ViewGenerator.generateTreeView(sessionContext.getUserContext());
            session.setAttribute("defaultTreeNode", treeNode);

            GenerateTree.getInstance().setMenuCornerMinusUri(request.getContextPath() + "/images/menu_corner_minus.gif");
            GenerateTree.getInstance().setMenuCornerPlusUri(request.getContextPath() + "/images/menu_corner_plus.gif");
            GenerateTree.getInstance().setMenuTeeMinusUri(request.getContextPath() + "/images/menu_tee_minus.gif");
            GenerateTree.getInstance().setMenuTeePlusUri(request.getContextPath() + "/images/menu_tee_plus.gif");
            GenerateTree.getInstance().setMenuBarUri(request.getContextPath() + "/images/menu_bar.gif");
            GenerateTree.getInstance().setMenuCornerUri(request.getContextPath() + "/images/menu_corner.gif");
            GenerateTree.getInstance().setMenuTeeUri(request.getContextPath() + "/images/menu_tee.gif");
            GenerateTree.getInstance().setMenuPixelUri(request.getContextPath() + "/images/menu_pixel.gif");

            String tree =
                GenerateTree.getInstance().processTree(treeNode.getDefaultMutableTreeNode(),
                                                       null
                                                      );
            session.setAttribute("treeview", tree);

            // Sets the user object in the session.
            userContext.setJbUser(user);
            session.setAttribute("user", userContext.getJbUser());

            return (mapping.findForward("success"));
        }
        catch (Exception se)
        {
            _logger.error(se.getMessage());
            msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                          new ActionMessage("error.service.unknown")
                         );
            saveErrors(request, msgErrors);

            return (mapping.findForward("service_error"));
        }
    }
}
